<?php
	class Rinvoices extends CI_Model
	{
		public $title;
		public $posted;
		public $content;
		
		public function __construct()
		{
			parent::__construct();
		}
		
		public function getAll()
		{
			$user =& Users::getInstance();
			$this->db->order_by('id',"DESC");
			$query = $this->db->get('invoices');
			$all = $query->result();
			
			foreach ($all as $i => $val) {
				$all[$i]->{"invoices"} = $this->countAll($all[$i]->id);
				$all[$i]->{"uinfo"} = $user->getUserInfo($all[$i]->uid, false);
			}
			
			return $all;
		}
		
		public function countAll($id) {
			$this->db->where('jid', $id);
			$this->db->where('type', 1);
			$this->db->order_by('date',"DESC");
			$q = $this->db->get('ainvoices');
			$all = $q->result();
			
			return $all;
		}
		
		public function getUID($user) {
			$this->db->or_where(array('name' => $user, 'user_id' => $user));
			$q = $this->db->get('users');
			$user = $q->row();
			
			return $user->uid;
		}
		
		public function usersList($search) {
			$this->db->where("name LIKE '".$search."%'");
			$this->db->or_where('user_id', $search);
			$q = $this->db->get('users');
			$users = $q->result();
			
			foreach ($users as $k => $user) {
				$users[$k]->id = $user->uid;
				$users[$k]->label = $user->name;
			}
			
			return $users;
		}
		
		public function getRI($id) {
			$this->db->where('id', $id);
			$q = $this->db->get('invoices');
			
			return $q->row();
		}
		
		public function insert($user, $period, $start, $remarks, $routes)
		{
			//$uid = $this->getUID($user);
			$uid = $user;
			$totalPrice = 0;
			$r = json_decode($routes);
			foreach ($r as $route) {
				$totalPrice += $route->totalprice;
			}
			
			if($this->db->insert('invoices',array(
				'uid'			=>	$uid,
				'period'		=>	$period,
				'remarks'		=>	$remarks,
				'start_date'	=>	$start,
				'next_issue'	=>	$start,
				'routes'		=>	$routes,
				'total_price'	=>	$totalPrice,
				'count'			=>	0
			))) { return true; }
		}
		
		public function update($id)
		{
			$title 		= $this->input->post('title');
			$posted		= time();
			$content	= $this->input->post('content');
			
			$this->db->where('id',$id);
			if($this->db->update('articles',array(
				'title'		=>	$title,
				'posted'	=>	$posted,
				'content'	=>	$content
			))) { return true; }
		}
		
		public function remove($id)
		{
			$this->db->delete('articles',array(
				'id'	=>	$id,
			));
			return true;
		}
	}
?>